package com.eece496.Server;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eece496.Database.Classroom;

/**
 * Servlet implementation class ProfAddClassroomServlet
 */
public class ProfAddClassroomServlet extends MasterServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProfAddClassroomServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Connect();
		String text = request.getParameter("text");
		String firstname = request.getParameter("firstname");
		String lastname = request.getParameter("lastname");
		String sectionNumber = request.getParameter("sectionNumber");
		String courseNumber = request.getParameter("courseNumber");
		
		ArrayList<String> ClassroomList = new ArrayList<String>();
		System.out.println(text);
		
		//Parse the list
		int firstchar = 0;
		for(int i=0; i < text.length() ; i++)
		{
			if(i==0)
			{
				firstchar = 0;
				//firstchar = text.charAt(0);
				//System.out.println(firstchar);
			}
			
			else if(i == (text.length()-1))
			{
				String str = text.substring(firstchar, text.length());
				ClassroomList.add(str);
				System.out.println(str);
			}
			
			else if(text.charAt(i) == ',')
			{
				String str = text.substring(firstchar, i);
				firstchar = i+1;
				ClassroomList.add(str);
				System.out.println(str);
			}
		}
		
		//Add classrooms to the Database
		for(String str: ClassroomList)
		{
			System.out.println(str);
			Classroom ClassDB = new Classroom(str,courseNumber,sectionNumber);
			ClassDB.Setup(connection);
			try {
				ClassDB.Insert();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("Exception Baby!!");
			}
		}
		
		request.setAttribute("courseNumber", courseNumber);
		request.setAttribute("sectionNumber", sectionNumber);
		request.setAttribute("firstname", firstname);
		request.setAttribute("lastname", lastname);
		
		request.getRequestDispatcher("/Professor/Professor-Course-Portal.jsp")
		.forward(request, response);
		
	}
}
